import {Injectable} from "@angular/core";
import {MsgResult} from "../models/msg-result";
import {LogUtil} from "./log-util";
import {Components, MsgConstants} from "../constants/constants";
import {Router} from "@angular/router";

@Injectable()
export class ResponseUtil {
  constructor(
    private logUtil:LogUtil,
    private router:Router
  ){}

  /**
   * 成功处理
   * @param result
   * @param callback
   */
  success(result:MsgResult | any,callback?:(this:void,result:MsgResult|any) => any) :void{
    if(this.preSuccess(result)){
      if(callback && typeof callback == "function"){
        callback(result);
      }
    }


  }

  error(message:string | any,callback?:(this:void,result:MsgResult|any) => any):void{
    if(callback && typeof callback == "function"){
      callback(message);
    }
    this.postError(message);
  }

  /**
   * 成功前置处理
   * @param result
   */
  preSuccess(result:MsgResult | any) :boolean{
    if(result && result.code){
      if(result.code != MsgConstants.MSG_CODE_OK){
        let resultCode =  Number.parseInt(result.code);
        if(resultCode != 51 && resultCode >= MsgConstants.MSG_CODE_AUTH_ERROR_MIN && resultCode <= MsgConstants.MSG_CODE_AUTH_ERROR_MAX){
          this.router.navigateByUrl(Components.authenComponent);
          return false;
        }
      }
      return true;
    }
    return false;
  }

  /**
   * 失败后置处理
   * @param message
   */
  postError(message :string | any):void{
    this.logUtil.error(message);
  }

  /**
   * 针对BS-Table的responseHandler的二次处理
   * @param result
   * @param callback
   * @returns {{total: (any|number), rows: (any|any[]|HTMLCollectionOf<HTMLTableRowElement>|string|number)}}
   */
  bsPageHandler(result:MsgResult | any,callback?:(this:void,result:MsgResult|any) => any):any{
    this.preSuccess(result);

      //处理result.data = null 的bug
      if(!result.data || !result.data.rows){
        result.data = {
          total:0,
          rows:[]
        };
      }
    if(callback && typeof callback == "function"){
      callback(result);
    }

    return {
      total:result.data.total,
      rows:result.data.rows
    }
  }

}
